package com.lenovo.manufacture;


import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.lenovo.manufacture.model.MaterialInfo;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Race8Activity extends AppCompatActivity {

    private ListView lv_eight;
    private List<MaterialInfo.DataBean> list = new ArrayList<>();
    private ArrayAdapter<MaterialInfo.DataBean> adapter;
    private TextView tv_sort_money;
    private TextView tv_sort_num;
    private Button btn_buy;
    public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#,###");
    private boolean sortFlagMoney, sortFlagNum = false;
    private final int iconUp = R.drawable.sanjao0002;
    private final int iconDown = R.drawable.sanjao0004;
    private ArrayList<MaterialInfo.DataBean> buyList = new ArrayList<>();
    public static final String KEY = "buy";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eight);
        initView();
        getData();
    }

    private void jumpWithBuyList() {
        if (buyList.isEmpty()) {
            Toast.makeText(Race8Activity.this, "购物车为空", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            MaterialInfo materialInfo = new MaterialInfo();
            materialInfo.setData(buyList);
            String json = new Gson().toJson(materialInfo);
            Intent intent = new Intent(this, ShoppingActivity.class);
            intent.putExtra(KEY, json);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(Race8Activity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    private void getData() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("http://192.168.1.103:8085/Interface/index/getMaterial")
                .method("POST", body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(Race8Activity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    MaterialInfo materialInfo = new Gson().fromJson(response.body().string(), MaterialInfo.class);
                    List<MaterialInfo.DataBean> data = materialInfo.getData();
                    if (!data.isEmpty()) {
                        list.clear();
                        list.addAll(data);
                        runOnUiThread(() -> {
                            adapter.notifyDataSetChanged();
                            Toast.makeText(Race8Activity.this, "成功", Toast.LENGTH_SHORT).show();
                        });
                    } else {
                        runOnUiThread(() -> Toast.makeText(Race8Activity.this, "data.isEmpty()", Toast.LENGTH_SHORT).show());
                    }
                } else {
                    runOnUiThread(() -> Toast.makeText(Race8Activity.this, "" + response.code(), Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void initView() {
        lv_eight = (ListView) findViewById(R.id.lv_eight);
        adapter = new ArrayAdapter<MaterialInfo.DataBean>(this, R.layout.item_eight_lv, list) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_eight_lv, parent, false);
                ViewHolder viewHolder = new ViewHolder(convertView);
                MaterialInfo.DataBean item = getItem(position);
                viewHolder.tv_item_eight_lv_id.setText("" + item.getMaterialId());
                viewHolder.tv_item_eight_lv_number.setText(DECIMAL_FORMAT.format(item.getNum()));
                viewHolder.tv_item_eight_lv_price.setText(DECIMAL_FORMAT.format(item.getPrice()));
                viewHolder.tv_item_eight_lv_shop.setText(item.getSupplyName());
                viewHolder.tv_item_eight_lv_shopname.setText(item.getContent());
                return convertView;
            }
        };
        lv_eight.setAdapter(adapter);
        tv_sort_money = (TextView) findViewById(R.id.tv_sort_money);
        tv_sort_money.setOnClickListener((view) -> {
            if (list.isEmpty()) return;
            Collections.sort(list, (o1, o2) -> {
                int c = sortFlagMoney ? 1 : -1;
                return (o1.getPrice() - o2.getPrice() )* c;
            });
            tv_sort_money.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, sortFlagMoney ? iconUp : iconDown, 0);
            sortFlagMoney = !sortFlagMoney;
            adapter.notifyDataSetChanged();
        });
        tv_sort_num = (TextView) findViewById(R.id.tv_sort_num);
        tv_sort_num.setOnClickListener((view) -> {
            if (list.isEmpty()) return;
            Collections.sort(list, (o1, o2) -> {
                int c = sortFlagNum ? 1 : -1;
                return (o1.getNum() - o2.getNum()) * c;
            });
            tv_sort_num.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, sortFlagNum ? iconUp : iconDown, 0);
            sortFlagNum = !sortFlagNum;
            adapter.notifyDataSetChanged();
        });
        btn_buy = (Button) findViewById(R.id.btn_buy);
        btn_buy.setOnClickListener((view)-> buySome());
    }


    private void buySome() {
        if (!list.isEmpty()) {
            ArrayList<MaterialInfo.DataBean> temp = new ArrayList<>(list);
            Collections.sort(temp, (o1, o2) -> o1.getPrice() - o2.getPrice());
            buyList.clear();
            for (int i = 0; i < 3; i++) {
                MaterialInfo.DataBean dataBean = list.get(i);
                if (dataBean != null) {
                    buyList.add(dataBean);
                } else {
                    return;
                }
            }
            temp = null;
            Toast.makeText(Race8Activity.this, "已加入购物车", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(Race8Activity.this, "list isEmpty", Toast.LENGTH_SHORT).show();
        }
    }

    public void toShop(View view) {
        jumpWithBuyList();
    }

    static class ViewHolder {
        public View rootView;
        public TextView tv_item_eight_lv_id;
        public TextView tv_item_eight_lv_shopname;
        public TextView tv_item_eight_lv_shop;
        public TextView tv_item_eight_lv_price;
        public TextView tv_item_eight_lv_number;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tv_item_eight_lv_id = (TextView) rootView.findViewById(R.id.tv_item_eight_lv_id);
            this.tv_item_eight_lv_shopname = (TextView) rootView.findViewById(R.id.tv_item_eight_lv_shopname);
            this.tv_item_eight_lv_shop = (TextView) rootView.findViewById(R.id.tv_item_eight_lv_shop);
            this.tv_item_eight_lv_price = (TextView) rootView.findViewById(R.id.tv_item_eight_lv_price);
            this.tv_item_eight_lv_number = (TextView) rootView.findViewById(R.id.tv_item_eight_lv_number);
        }
    }
}
